package com.example.networktest;

import android.graphics.ImageDecoder;
import android.os.Bundle;


import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.example.networktest.Entity.App;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Observer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView responseText;



    public static String convertOctalToUtf8(String octalString) {
        // 分割八进制转义序列
        String[] octalValues = octalString.split("\\\\");
        byte[] bytes = new byte[octalValues.length - 1];

        // 将每个八进制转义序列转换为字节
        for (int i = 1; i < octalValues.length; i++) {
            bytes[i - 1] = (byte) Integer.parseInt(octalValues[i], 8);
        }

        // 将字节数组转换为UTF-8字符串
        return new String(bytes, StandardCharsets.UTF_8);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);





        // 包含八进制转义序列的字符串
        String octalString = "\\346\\213\\222\\347\\273\\235\\344\\270\\215\\344\\272\\206\\346\\227\\227\\350\\242\\215";

        // 将八进制转义序列转换为UTF-8字符串
        String utf8String = convertOctalToUtf8(octalString);
        Log.e("My", utf8String);

        My.MainMessage mainMessage = My.MainMessage.newBuilder()
            .setField1(0)
            .setField2(1844674407370955L)
            .setField3(0)
            .setField4(1)
            .setField5(My.NestedMessage.newBuilder()
                .setField1("7435565178663603494")
                .setField2("\\345\\205\\263\\346\\263\\250\\346\\210\\221\\344\\275\\240\\344" +
                    "\\274\\232\\346\\232\\264\\345\\257\\214\\342\\235\\233\\313\\223\\342\\227" +
                    "\\236\\313\\202\\314\\265\\342\\234\\247\\360\\237\\224\\235\\n@\\346\\242" +
                    "\\223\\344\\270\\200\\345\\255\\246\\345\\247\\220 " +
                    "\\345\\205\\250\\347\\275\\221\\345\\217\\252\\346\\234\\211\\350\\277\\231" +
                    "\\344\\270\\244\\345\\217\\267 " +
                    "\\345\\205\\266\\344\\273\\226\\351\\203\\275\\346\\230\\257\\345\\201\\207" +
                    "\\345\\230\\237\\357\\274\\201\\n\\345\\217\\252\\345\\233\\236\\345\\244" +
                    "\\215\\344\\270\\223\\345\\261\\236\\344\\274\\232\\345\\221\\230\\345\\256" +
                    "\\235\\345\\256\\235 \\350\\277\\233\\344\\270\\223\\345\\261\\236\\351\\200" +
                    "\\201\\351\\227\\262\\347\\275\\256\\360\\237\\222\\234\\n\\346\\251\\261" +
                    "\\347\\252\\227\\345\\245\\275\\347\\211\\251\\342\\254\\207\\357\\270\\217")
                .setField3(1731227945)
                .setField4(My.NestedMessage.SubMessage.newBuilder()
                    .setField1("99195767597")
                    .setField2(My.NestedMessage.SubMessage.InnerMessage.newBuilder()
                        .setField7(0x32353230383338L).build()
                        )
                    .setField3(My.NestedMessage.SubMessage.AnotherInnerMessage.newBuilder().setField160774732(0xae909ff0).build())
                    .setField5("\u6d4b\u8bd5\u6d88\u606f")
                    .setField6(My.NestedMessage.SubMessage.Image.newBuilder()
                        .setField1("1080x1080/aweme-avatar/tos-cn-avt-0015_9a6407767571ea00febeb1daa903f2b3")


                        .build())
                    .setField7(My.NestedMessage.SubMessage.Image.newBuilder()
                        .setField1("100x100/aweme-avatar/tos-cn-avt-0015_9a6407767571ea00febeb1daa903f2b3")

                        .build())
                    .build())
                .build())
            .build();



        // 将 Protobuf 消息转换为 JSON 字符串
        try {

            String json = JsonFormat.printer().print(mainMessage);
            Log.e("CharlieJ","JSON: " + json);

        } catch (IOException e) {
            e.printStackTrace();
        }





        Button sendRequest1 = (Button) findViewById(R.id.send_requestSync);
        Button sendRequest2 = (Button) findViewById(R.id.send_requestAsync);
        Button sendRequest3 = (Button) findViewById(R.id.Retrofit_request);

        ImageView iv = findViewById(R.id.iv);
        sendRequest1.setOnClickListener(this);
        sendRequest2.setOnClickListener(this);
        sendRequest3.setOnClickListener(this);


        Glide.with(this)
            .load("https://img1.baidu.com/it/u=1765276815,3404727259&fm=253&fmt=auto?w=1422&h=800")
            .thumbnail(0.1f)
            .into(iv);


    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_requestSync) {
//            sendRequestWithHttpURLConnection();
            sendRequestWithOkHttpSync();
        }

        if (v.getId() == R.id.send_requestAsync) {
//            sendRequestWithHttpURLConnection();
            sendRequestWithOkHttpASync();
            
        }

        if (v.getId() == R.id.Retrofit_request) {
//            sendRequestWithHttpURLConnection();
            try {
                sendRequestWithOkHttpRetrofit();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }


    // 使用 HttpURLConnection 发送网络请求
    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    // 下面对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // 使用 okhttp发送网络请求
    private void sendRequestWithOkHttpSync() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                        // 指定访问的服务器地址是 某个网站域名
                            .url("http://httpbin.org/get?a=1&b=2")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();

                    Log.d("sync", responseData);
//                    parseJSONWithGSON(responseData);
//                    parseJSONWithJSONObject(responseData);
//                    parseXMLWithSAX(responseData);
//                    parseXMLWithPull(responseData);
//                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendRequestWithOkHttpRetrofit() throws IOException {

        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
        HttpBinRequest httpBinRequest = retrofit.create(HttpBinRequest.class);
        retrofit2.Call<ResponseBody> call =
            httpBinRequest.getRequest("zwj", "123456");

        // 异步请求，用enqueue（new 接口 。。。）方法
        // 同步请求 仍然也是 execute()方法，不过必须放在 new Thread（）子线程中去运行，

        retrofit2.Response<ResponseBody> responseBodyResponse = call.execute();
        Log.d("charlieJ", responseBodyResponse.body().string());


        // 异步请求
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call,
                retrofit2.Response<ResponseBody> response) {
                try {
                    Log.d("charlieJ", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

            }
        });




    }

    private void sendRequestWithOkHttpASync() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            // 指定访问的服务器地址是 某个网站域名
            .url("http://httpbin.org/get?a=1&b=2")
            .build();

        // 异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)
                throws IOException {
                if(response.isSuccessful()){}
                Log.d("Async",response.body().string());
            }
        });

    }



    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d("MainActivity", "id is " + id);
                Log.d("MainActivity", "name is " + name);
                Log.d("MainActivity", "version is " + version);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());
        for (App app : appList) {
            Log.d("MainActivity", "id is " + app.getId());
            Log.d("MainActivity", "name is " + app.getName());
            Log.d("MainActivity", "version is " + app.getVersion());
        }
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {



            @Override
            public void run() {
                // 在这里进行UI操作，将结果显示到界面上
                responseText.setText(response);
            }
        });
    }


    // RxJava
    public void fun(){


        Observable<String> observable = Observable.create(emitter -> {
            try {
                emitter.onNext("Hello");
                emitter.onNext("RxJava");
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        });




        Observable<String> observable2 = Observable.just("Hello", "RxJava");
        Observable<Integer> observable3 = Observable.range(1, 5); // 发射 1 到 5


    }



}
